package com.china08.yxyapi.api.home.kecheng.sync;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.http.MediaType;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.china08.yxyapi.api.YxyApiBaseController;
import com.china08.yxyapi.model.YxyApiPageReqModel;
import com.china08.yxyapi.model.YxyApiRespModel;

/**
 * 同步课程--列表页--按学段、学科、版本、分类、是否付费 进行课程查询
 * 
 * @author LiuWeidong
 *
 */
@CrossOrigin
@RestController
public class KechengSyncListSrhController extends YxyApiBaseController {

    // @Autowired
    // private YxyLessonsSynchroCatalogRepository
    // yxyLessonsSynchroCatalogRepository;
    //
    // @Autowired
    // private YxyLessonsSynchroLessonRepository
    // yxyLessonsSynchroLessonRepository;
    //
    // /** 学科 */
    // @Autowired
    // private YxyResSubjectRepository yxyResSubjectRepository;
    //
    // /** 版本 */
    // @Autowired
    // private YxyResVersionRepository yxyResVersionRepository;
    //
    // /** 分类 */
    // @Autowired
    // private YxyLessonsSynchroGradeRepository
    // yxyLessonsSynchroGradeRepository;

    @Autowired
    JdbcTemplate JdbcTemplate;

    @RequestMapping(value = "/api_yw/home/kecheng/sync/version/srh", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public Page<RespModel> find(HttpServletRequest request, HttpServletResponse response, @RequestBody ReqModel reqModel) {
        long l = System.currentTimeMillis();
        String stageId = reqModel.stageId;
        String subjectId = reqModel.subjectId;
        String versionId = reqModel.versionId;
        String gradeId = reqModel.gradeId;
        Integer vip = reqModel.vip;
        String lastModifiedDate = reqModel.lastModifiedDate;
        String ep = reqModel.ep;
        String pv = reqModel.pv;
        String name = (StringUtils.isNotBlank(reqModel.name)) ? "%" + reqModel.name + "%" : "";

        StringBuffer sb = new StringBuffer();
        sb.append(" SELECT                                               ");
        sb.append("   t2.id                                              ");
        sb.append(" FROM                                                 ");
        sb.append("   yxy_lessons.yxy_lessons_synchro_catalog t1             ");
        sb.append("   LEFT JOIN yxy_lessons.yxy_lessons_synchro_lesson t2    ");
        sb.append("     ON t1.id = t2.catalog_id                         ");
        sb.append(" WHERE 1 = 1                                          ");
        sb.append(" and t2.id is not null ");
        sb.append(" and t2.status = 2 ");
        sb.append(" and t2.is_visible = 1 ");

        List<Object> paramList = new ArrayList<>();

        if (StringUtils.isNotBlank(stageId)) {
            sb.append("   AND t1.stage_id = ?                            ");
            paramList.add(stageId);
        }
        if (StringUtils.isNotBlank(subjectId)) {
            sb.append("   AND t1.subject_id = ?                          ");
            paramList.add(subjectId);
        }
        if (StringUtils.isNotBlank(versionId)) {
            sb.append("   AND t1.version_id = ?                          ");
            paramList.add(versionId);
        }
        if (StringUtils.isNotBlank(gradeId)) {
            sb.append("   AND t1.grade_id = ?                               ");
            paramList.add(gradeId);
        }
        if (null != vip) {
            sb.append("   AND t2.Vip = ?                               ");
            paramList.add(vip);
        }
        if (StringUtils.isNotBlank(reqModel.name)) {
            sb.append("   AND t2.name like ?                                ");
            paramList.add(name);
        }

        List<String> countList = JdbcTemplate.queryForList(sb.toString(), paramList.toArray(), String.class);

        System.out.println("l1:" + (System.currentTimeMillis() - l));
        // 最近更新、评分最高、学习最多 排序
        if (StringUtils.isNotBlank(lastModifiedDate)) {
            sb.append(" ORDER BY t2.up_date DESC,t2.name DESC   ");
        }
        if (StringUtils.isNotBlank(ep) && StringUtils.isBlank(lastModifiedDate)) {
            sb.append(" ORDER BY t2.ep DESC  ");
        }
        if (StringUtils.isNotBlank(pv) && StringUtils.isBlank(ep) && StringUtils.isBlank(lastModifiedDate)) {
            sb.append(" ORDER BY t2.vv DESC ");
        }

        sb.append(" limit " + (reqModel.page * reqModel.size) + "," + reqModel.size);

        List<String> idList = JdbcTemplate.queryForList(sb.toString(), paramList.toArray(), String.class);
        long l2 = System.currentTimeMillis();
        System.out.println("l2:" + (l2 - l));
        List<RespModel> returnLst = new ArrayList<>();
        for (String id : idList) {
            RespModel model = new RespModel();

            StringBuffer sb1 = new StringBuffer();
            sb1.append(" SELECT                       ");
            sb1.append("   lesson.id leseeonId,      ");
            sb1.append("    subjects.name sub,       ");
            sb1.append("    versions.name ver,       ");
            sb1.append("    lesson.vip vip,          ");
            sb1.append("    lesson.cover cover,      ");
            sb1.append("    lesson.count COUNT,      ");
            sb1.append("    lesson.duration duration,      ");
            sb1.append("    lesson.name lessonName,       ");
            sb1.append("    lesson.ep ep,                  ");
            sb1.append("    lesson.ep_times eptimes,       ");
            sb1.append("    lesson.vv vv,                 ");
            sb1.append("    catalog.stage_id stageId,       ");
            sb1.append("    grade.name gradeName       ");
            sb1.append(" FROM                         ");
            sb1.append("   yxy_lessons.yxy_lessons_synchro_lesson lesson                  ");
            sb1.append("   LEFT JOIN yxy_lessons.yxy_lessons_synchro_catalog catalog      ");
            sb1.append("     ON (lesson.catalog_id = catalog.id)                          ");
            sb1.append("   LEFT JOIN yxy_lessons.yxy_lessons_synchro_grade grade          ");
            sb1.append("     ON (catalog.grade_id = grade.id)                             ");
            sb1.append("   LEFT JOIN yxy_res.yxy_res_subject subjects                     ");
            sb1.append("     ON (catalog.subject_id = subjects.id)                        ");
            sb1.append("   LEFT JOIN yxy_res.yxy_res_version versions                     ");
            sb1.append("     ON (catalog.version_id = versions.id)                        ");
            sb1.append(" WHERE lesson.id = ?                                              ");
            List<Map<String, Object>> guardianMapList = JdbcTemplate.queryForList(sb1.toString(), new Object[] { id });
            if (guardianMapList.size() > 0) {
                for (Map<String, Object> map : guardianMapList) {

                    model.gradeName = map.get("name") + "";
                    model.subjectName = map.get("sub") + "";
                    model.versionName = map.get("ver") + "";
                    model.cover = map.get("cover") + "";
                    model.name = map.get("lessonName") + "";
                    model.lessonId = map.get("leseeonId") + "";
                    model.gradeName = map.get("gradeName") + "";

                    Object obj0 = map.get("vip");
                    if (obj0 != null) {
                        model.vip = Integer.parseInt(map.get("vip") + "");
                    }

                    Object obj1 = map.get("COUNT");
                    if (obj1 != null) {
                        model.count = Integer.parseInt(map.get("COUNT") + "");
                    }

                    Object obj2 = map.get("duration");
                    if (obj2 != null) {
                        model.duration = Integer.parseInt(map.get("duration") + "");
                    }

                    Object obj4 = map.get("vv");
                    if (obj4 != null) {
                        model.vv = Integer.parseInt(map.get("vv") + "");
                    }

                    Object obj5 = map.get("eptimes");
                    if (obj5 != null) {
                        model.EpTimes = Integer.parseInt(map.get("eptimes") + "");
                    }

                    Object obj6 = map.get("ep");
                    if (obj6 != null) {
                        model.ep = (float) map.get("ep");
                    }
                }
            }
            returnLst.add(model);
        }

        long l3 = System.currentTimeMillis();
        System.out.println("l3:" + (l3 - l2));

        Pageable pageable = reqModel.getPageable(Direction.DESC, "createdDate");
        Page<RespModel> page = new PageImpl<>(returnLst, pageable, countList.size());

        return page;
    }

    private Float Float(String string) {
        // TODO Auto-generated method stub
        return null;
    }

    /* 请求参数 */
    protected static class ReqModel extends YxyApiPageReqModel {

        // 学段ID
        public String stageId;

        // 学科ID
        public String subjectId;

        // 版本ID
        public String versionId;

        // 分类ID
        public String gradeId;

        // 课程名称
        public String name;

        // 是否vip
        public Integer vip;

        public Integer pageNum;

        // 按最近更新排序(如果点击前台传“1”)
        public String lastModifiedDate;

        // 按评分最高排序(如果点击前台传“1”)
        public String ep;

        // 按学习最多排序(如果点击前台传“1”)
        public String pv;
    }

    /* 响应参数 */
    protected static class RespModel extends YxyApiRespModel {

        // 学年
        public String gradeName;
        // 学科
        public String subjectName;
        // 版本
        public String versionName;
        // 学段
        public String stage;

        // 是否vip 0--非vip 1--vip课程
        public Integer vip = 0;
        // 封面
        public String cover;
        // 总课时
        public Integer count = 0;
        // 总时长
        public Integer duration = 0;
        // 课程名称
        public String name;
        // 课程评分（所有评分之和处于评分人数即综合评分）
        public Float ep = 0.0f;
        // 评价人数
        public Integer EpTimes = 0;
        // 学习人数
        public Integer vv = 0;
        // 课程Id
        public String lessonId;
    }
}
